package com.tj.jinzao.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tandong.bottomview.view.BottomView;
import com.tj.jinzao.R;
import com.tj.jinzao.activity.HealthReportDetailActivity;
import com.tj.jinzao.adapter.HealthListItemAdapter;
import com.tj.jinzao.api.ApiRetrofit;
import com.tj.jinzao.api.ApiService;
import com.tj.jinzao.api.SubscriberCallBack;
import com.tj.jinzao.base.BaseDataListFragment;
import com.tj.jinzao.base.IBaseView;
import com.tj.jinzao.model.DeleteMessage;
import com.tj.jinzao.model.Health;
import com.tj.jinzao.model.LineDataBean;
import com.tj.jinzao.model.QueartDataBean;
import com.tj.jinzao.model.ResultResponse;
import com.tj.jinzao.presenter.HealthPresenter;
import com.tj.jinzao.utils.ToastUtils;
import com.tj.jinzao.widgets.ChartLineView;
import com.tj.jinzao.widgets.ChartQView;
import com.tj.jinzao.widgets.EmptyView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * 健康报告列表fragment
 * Created by wjy on 2019/1/1.
 */
public class HealthReportListFragment extends BaseDataListFragment<List<Health>, HealthPresenter, Health> implements IBaseView<List<Health>> {

    //家庭账号
    protected final static String ARG_FAMILY_ID = "family_id";

    private long mFamilyId;
    private ChartLineView chartLineView;
    private ChartQView chartView;
    float width;
    float height;

    public static HealthReportListFragment newInstance(long familyId) {
        HealthReportListFragment fragment = new HealthReportListFragment();
        if (fragment != null) {
            Bundle args = new Bundle(3);
            args.putString(ARG_TAG_ID, String.valueOf(1));
            args.putInt(ARG_LOAD_ID, 1);
            args.putLong(ARG_FAMILY_ID, familyId);
            args.putInt(ARG_LAYOUT_RES_ID, R.layout.base_fragment_item_layout);
            fragment.setArguments(args);
        }
        return fragment;
    }
    private TextView score,time,health;
    private ImageView image_time;
    private LinearLayout content_lay;
    @Override
    protected void createView(LayoutInflater inflater, View view) {
        mFamilyId = getArguments().getLong(ARG_FAMILY_ID);
        View headView = inflater.inflate(R.layout.head_report, null);
        headView.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        mListView.addHeaderView(headView);
        chartLineView=headView.findViewById(R.id.chartLineView);
        chartView=headView.findViewById(R.id.chartView);
        score=headView.findViewById(R.id.score);
        content_lay=headView.findViewById(R.id.content_lay);
        time=headView.findViewById(R.id.time);
        health=headView.findViewById(R.id.health);
        image_time=headView.findViewById(R.id.image_time);
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        width=dm.widthPixels;
        height=dm.heightPixels;
        pos=0;

    }
    private int pos;
    private void initQuart(List<Health> list_h){
        chartView.initQuart(width,height,list_h);
        handler.sendEmptyMessageDelayed(2,200);
    }
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(lists.size()==1){
                chartView.setPosition(1);
            }else {
                chartView.setPosition(lists.size()>15?15:lists.size()-1);
            }

        }
    };

    private void init(List<Health> list_h) {
        chartLineView.init(width,height,list_h);
    }
    private BottomView bottomView;
    private void showPopWindow(Long id){
        bottomView=new BottomView(getActivity(), com.netease.nim.uikit.R.style.BottomViewTheme_Defalut, com.netease.nim.uikit.R.layout.item_select);
        bottomView.setAnimation(com.netease.nim.uikit.R.style.myStyle);
        bottomView.dismissBottomView();
        bottomView.showBottomView(false);
        TextView txt_1= bottomView.getView().findViewById(com.netease.nim.uikit.R.id.txt_1);
        TextView txt_2= bottomView.getView().findViewById(com.netease.nim.uikit.R.id.txt_2);
        View view_line=bottomView.getView().findViewById(com.netease.nim.uikit.R.id.view_line);
        view_line.setVisibility(View.GONE);
        txt_1.setText("删除");
        txt_2.setVisibility(View.GONE);
        TextView txt_exit= bottomView.getView().findViewById(com.netease.nim.uikit.R.id.txt_exit);
        txt_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deleteMessage(id);
                bottomView.dismissBottomView();

            }
        });
        txt_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomView.dismissBottomView();
            }
        });

    }
    protected ApiService mApiService = ApiRetrofit.getInstance().getApiService();

    private CompositeSubscription mCompositeSubscription;

    @Override
    public void onDestroy() {
        super.onDestroy();
        detachView();
    }

    public void detachView() {
        onUnsubscribe();
    }
    public void addSubscription(Observable observable, Subscriber subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

    //RXjava取消注册，以避免内存泄露
    public void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }
    private void deleteMessage(Long id){
        addSubscription(mApiService.deleteReport(id), new SubscriberCallBack<DeleteMessage>(getActivity()) {
            @Override
            protected void onSuccess(DeleteMessage list) {
                ToastUtils.showToast(getActivity(),"删除成功");
                requestData();
            }

            @Override
            protected void onFailure(ResultResponse response) {

            }

            @Override
            protected boolean isShowProgress() {
                return false;
            }

            @Override
            protected void onPageSuccess(int currentPage, int allPage, int allSize) {
            }
        });

    }

    @Override
    public void onRequestNoData(String message) {
        setEmptyDataView();
    }

    @Override
    protected HealthPresenter createPresenter() {
        return new HealthPresenter(this);
    }
    private HealthListItemAdapter healthListItemAdapter;


    @Override
    protected RecyclerView.Adapter createAdapter() {
        healthListItemAdapter= new HealthListItemAdapter(mContext, mData,chartView);
        return healthListItemAdapter;
    }

    @Override
    protected void requestData() {
        mPresenter.getHealthList(mFamilyId,Long.parseLong(getActivity().getIntent().getStringExtra("userId")));
        chartView.setOnChartClickListener(new ChartQView.onChartClickListener() {
            @Override
            public void onclick(int id) {
                for (int i=0;i<lists.size();i++){
                    if(lists.get(i).getId()==id){
                        score.setText(lists.get(i).getScores()+"分");
                        time.setText(lists.get(i).getReportTime());
                        health.setText("检测结果："+lists.get(i).getScoreText());
                    }
                }

            }
        });
        healthListItemAdapter.setOnLongCickLinstener(new HealthListItemAdapter.OnLongCickLinstener() {
            @Override
            public void onLongClick(Long id) {
                showPopWindow(id);
            }
        });
    }

    @Override
    protected void setEmptyDataView() {
        mEmptyView.setVisibility(View.VISIBLE);
        mEmptyView.setState(EmptyView.State.NO_DATA, "没有数据");
    }
    private boolean isFirst;
    private List<Health> lists=new ArrayList<>();

    @Override
    public void onRequestSuccess(List<Health> list) {
        super.onRequestSuccess(list);
        if (mPageNo <= 1) {
            mData.clear();
        }
        lists.clear();
        if(list.size()>15){
            for (int i=0;i<15;i++){
                lists.add(list.get(i));
            }
        }else {
            for (int i=0;i<list.size();i++){
                lists.add(list.get(i));
            }
        }
        Collections.reverse(lists);
        mData.addAll(list);
        showListView();
        if(lists.size()==0){
            content_lay.setVisibility(View.GONE);
            image_time.setVisibility(View.GONE);
            return;
        }
        score.setText(lists.get(lists.size()>15?14:lists.size()-1).getScores()+"分");
        time.setText(lists.get(lists.size()>15?14:lists.size()-1).getReportTime());
        health.setText("检测结果："+lists.get(lists.size()>14?14:lists.size()-1).getScoreText());
        if(isFirst==false&&lists.size()>0){
            init(lists);
            initQuart(lists);
            isFirst=true;
        }
        chartView.setInvidata();
        handler.sendEmptyMessageDelayed(2,200);


    }

    @Override
    protected boolean resolveData(List<Health> health) {
        return false;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
//        int position = (Integer) v.getTag(R.id.position);
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void itemClicked(int position, Health data) {
        HealthReportDetailActivity.start(mContext, data.getId());
    }

}
